/**
 * 工具类、实用函数
 */

const trimFunc = require('lodash/trim');
const escapeFunc = require('lodash/escape');
const isEmptyFunc = require('lodash/isEmpty');
const moment = require("moment");
const globalConfig = require('../../config/global_config');
const resConfig = globalConfig.res;
const emailReg = new RegExp('^[\\w\\.]+@\\w+\\.\\w+$');
const userIdReg = new RegExp('^[\\w\\.]+$');
const ipReg = new RegExp('^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?).){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$');

const publicIp = require('public-ip');

/**
 * 找出第一个符合条件的数组成员
 */
exports.findItem = function (arr, key, value) {
    return arr.find(item => item[key] === value)
}

exports.findNameById = function (arr, id) {
    let item = findItem(arr, 'id', id)
    return item ? item.name : ''
}

exports.isObjectLike = function (value) {
    return !!value && typeof value == 'object'
}

exports.isNumber = function (value) {
    return typeof value == 'number' || (this.isObjectLike(value) && Object.prototype.toString.call(value) == '[object Number]')
}

// 20180328为了兼容之前的参数类型判断，新建了一个判断方法
exports.isNumber2 = function (value) {
    return typeof value === 'number' && !isNaN(value)
}

exports.isDate = function (value, fmt) {
    try {
        let f = 'YYYYMMDD';
        if (fmt) {
            f = fmt;
        }
        // return !(moment(value, f).toString() == 'Invalid date');
        return moment(value, f, true).isValid();
    } catch (err) {
        return false;
    }
}

/**
 * 转义sql参数防止注入攻击
 */
exports.escapeSql = function (string) {
    return escapeFunc(string)
}

/**
 * 去掉字符串前后空白或指定字符
 */
exports.trim = function (string, chars) {
    return trimFunc(string, chars) // es6 String.trim 不支持 chars 参数
}

/**
 * Checks if value is an empty object, collection, map, or set.
 */
exports.isEmpty = function (value) {
    return isEmptyFunc(value)
}

/**
 * string to ISODate
 */
exports.toISODate = function (str, fmt) {
    let f = 'YYYYMMDD';
    if (fmt) {
        f = fmt;
    }
    return moment(str, f);
}

/**
 * format date
 */
exports.fmtDate = function (full_date, fmt) {
    let f = 'YYYYMMDDHHmmssSSS';
    if (fmt) {
        f = fmt;
    }
    return moment(full_date, 'YYYYMMDDHHmmssSSS').format(f);
}

/**
 * format date
 */
exports.fmtUnix = function (full_date, fmt) {
    let f = 'YYYYMMDDHHmmssSSS';
    if (fmt) {
        f = fmt;
    }
    return moment.unix(full_date).format(f);
}

/**
 * 取文件后缀名
 * @param filepath
 * @returns {string}
 * @constructor
 */
exports.getFileExt = function (filepath) {
    if (filepath != "") {
        var pos = "." + filepath.replace(/.+\./, "");
        return pos;
    }
}

exports.getFileNameFromUrl = function (url) {
    if (url) {
        return url.substring(url.lastIndexOf('/') + 1);
    } else {
        return '';
    }
}

/**
 * 图片url补齐
 */
exports.getAvatarUrl = function (url) {
    let ret = '';
    if (url) {
        ret = resConfig.base_pic_uri + url;
    }
    return ret;
}
exports.getCaptureUrl = function (url) {
    let ret = '';
    if (url) {
        ret = resConfig.base_record_uri + url;
    }
    return ret;
}
exports.getJulongCaptureUrl = async function (url) {
    let ret = '';
    const public_ip = await publicIp.v4()
    if (url) {
        ret = public_ip+':'+globalConfig.config.res_host.port+resConfig.julong_record_dirname+url;
    }
    return ret;
}

exports.formatCaputureUrl = (ip,name) => {
    // 生产环境下用公网ip
    ip = process.env.NODE_ENV === 'production' ? ip : globalConfig.config.web_host.ip;
    return `http://${ip}:${globalConfig.config.server_host.port}${resConfig.julong_record_dirname}${name}`;
}

exports.getBase64ImgUrl = function (url) {
    let ret = '';
    if (url) {
        ret = 'data:image/png;base64,' + url;
    }
    return ret;
}

/**
 * 分页处理
 * @param pageNumber
 * @param pageSize
 * @param model
 * @param queryParams
 * @param opt
 * @param populate
 * @param sortParams
 * @returns {Promise.<{pageNumber: number}>}
 */
exports.pageQuery = async function (pageNumber, pageSize, model, queryParams, opt, populate, sortParams) {
    const size = Number(pageSize)
    const start = (pageNumber - 1) * size;
    let ret = {
        pageNumber: Number(pageNumber)
    };

    // 查询数量
    const count = await model.find(queryParams, opt).count();
    // 查询一页的记录
    const records = await model.find(queryParams, opt).skip(start).limit(size).populate(populate).sort(sortParams);
    ret.pageCount = Math.ceil(count / size);
    ret.total = count;
    ret.results = records;
    return ret;
};

exports.paddingLeft = function (num, n) {
    let len = num.toString().length;
    while (len < n) {
        num = "0" + num;
        len++;
    }
    return num;
};

/**
 * 校验 邮箱格式是否合法
 * @param str
 * @returns {boolean}
 */
exports.isEmail = function (str) {
    return emailReg.test(str)
}

/**
 * 校验 IP格式是否合法
 * @param str
 * @returns {boolean}
 */
exports.isIp = function (str) {
    return ipReg.test(str)
}

/**
 * 检验user_id是否合法
 * @param user_id
 */
exports.checkUserId = function (user_id) {
    return userIdReg.test(user_id)
}

/**
 * 相似度处理
 */
exports.fmtSimilarity = function (score) {
    return Math.floor(score * 100) + '%';
}
